package com.hns.can.master.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.cache.annotation.CacheEvict;
import com.hns.can.base.entity.SysAuthorityResourceEntity;
import com.hns.can.base.entity.SysCodeDscEntity;
import com.hns.can.base.entity.SysRoleEntity;
import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.constants.GlobalConst;
import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.formula.FillCodeDscValue;
import com.hns.can.common.formula.FillParamsVo;
import com.hns.can.master.entity.BaseOrganEntity;
import com.hns.can.master.vo.LeftOrgVo;
import com.hns.frame.enumrate.EnabledSt;
import com.hns.frame.service.CommonService;
import com.hns.frame.util.ReflectUtil;
import com.hns.tool.pub.DataUtil;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.SearchConditionVo;
import com.hns.tool.pub.UtilString;

/**
 * 组织机构的相关业务
 * @author:lan
 * @email:763836737@qq.com
 * @version Revision 2.0.0
 */
@Service
public class BaseOrganService extends CommonService {
    
	/**
	 * 填充代码描述service
	 */
	@Autowired
    private FillCodeDscValue codeDscValue;
	
	/**
	 * 新增一个组织机构
	 * @param entity
	 * @param user
	 * @throws Exception
	 * @author:lan
	 * @email:763836737@qq.com
	 */
    @SuppressWarnings("unchecked")
    @CacheEvict(value=GlobalConst.CACHE_KEY_BASE_ORGAN, key="#user.getCorpId()")
    @Transactional
    public String saveBaseOrgan(BaseOrganEntity entity, SysUserEntity user) throws Exception {
        // 实体信息
    	String organId = UtilString.getUUID();
        entity.setOrganId(organId);
        // 生成流水号，算上停用状态的
        Integer lowerCnt = this.getChildNodeCnt(entity.getParentOrganId(), user);
        String currentId = commonEntityDao.find(entity.getParentOrganId(), BaseOrganEntity.class).getSno();
        String sno = DataUtil.buildId(currentId, 3, lowerCnt);
        entity.setSno(sno);
        
        entity.setEnabledSt(EnabledSt.ENABLE.getFlag());  // 启用状态
        entity.setCrtTime(new Date());
        entity.setCrtUser(user.getAcctName());
        
        // 校验同一级不能同名，不算停用状态的
        this.check("baseOrgan.checkOrganName", entity, "您输入的机构名称已经存在！");
        // 校验机构编码是否存在，不算停用状态的
        this.check("baseOrgan.checkOrganCd", entity, "您输入的机构编码已经存在！");
        commonEntityDao.save(entity);
        // 对应增加当前用户的角色及其上级角色的数据权限 upt by jeffxu 150327
        List<SysRoleEntity> list = PubUtil.convertListMapToObject(
            this.sqlMapDao.selectList("sysUser.getAllRoleByUserId", user.getId()), SysRoleEntity.class);
        for(SysRoleEntity role : list){
            SysAuthorityResourceEntity resEntity = new SysAuthorityResourceEntity();
            resEntity.setId(UtilString.getUUID());
            resEntity.setRoleId(role.getId());
            resEntity.setResDataId(entity.getOrganId());
            resEntity.setCreateTs(new Date());
            resEntity.setIsFull("1");
            resEntity.setResType("RES00001");
            commonEntityDao.save(resEntity);
        }
        return organId;
    }
    
    /**
     * 修改组织机构对象
     * @param entity
     * @param user
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @CacheEvict(value=GlobalConst.CACHE_KEY_BASE_ORGAN, key="#user.getCorpId()")
    @Transactional
    public void updateBaseOrgan(BaseOrganEntity entity, SysUserEntity user) throws Exception {
        // 实体信息 ==========================
        BaseOrganEntity tmpEntity = commonEntityDao.find(entity.getOrganId(), BaseOrganEntity.class);
        entity.setCrtTime(tmpEntity.getCrtTime());
        entity.setCrtUser(tmpEntity.getCrtUser());
        entity.setSno(tmpEntity.getSno());
        entity.setEnabledSt(tmpEntity.getEnabledSt());
        
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        
        // 后台校验
        // 校验同一级不能同名，不算停用状态的，排除自身
        this.check("baseOrgan.checkOrganName", entity, "您输入的机构名称已经存在！");
        // 校验机构编码是否存在，不算停用状态的
        this.check("baseOrgan.checkOrganCd", entity, "您输入的机构编码已经存在！");
        commonEntityDao.update(entity);
    }
	
    /**
     * 获取组织机构的数据，并且是启用状态
     * @param user
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
	@SuppressWarnings({"unchecked" })
    @Transactional
    public List<BaseEntity> getBaseOrganList(SysUserEntity user)  throws Exception{
	    String userId = user.getId();
	    List<BaseEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseOrgan.getBaseOrganList", userId), BaseOrganEntity.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("corpName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo = new FillParamsVo("corpId", map);
        codeDscValue.fillInfoValue(list, new String[]{GlobalConst.CACHE_KEY_SYS_CORP}, vo);
        
      /*  map = new HashMap<String,String>();
        for(Object entity : list){
            if(PubUtil.isEmpty(ReflectUtil.getFieldValue(entity, "provinceId"))){
                continue;
            }
            map.put("cityName", ReflectUtil.getFieldValue(entity, "provinceId").toString());
        }
        codeDscValue.fillCodeDscValue(list, map);*/
	    return list;
    }
	
	/**
	 * 获取组织机构的数据用于设备注册
	 * @param user
	 * @return
	 * @author:lan
	 * @email:763836737@qq.com
	 */
	@SuppressWarnings({"unchecked" })
    @Transactional
	public List<BaseEntity> getBaseOrganListForEquipment(
			SysUserEntity user) throws Exception {
	    String userId = user.getId();
	    List<BaseEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseOrgan.getBaseOrganListForEquipment", userId), BaseOrganEntity.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("corpName", GlobalConst.DEFAULT_CACHE_VALUE);   
        FillParamsVo vo = new FillParamsVo("corpId", map);
        codeDscValue.fillInfoValue(list, new String[]{GlobalConst.CACHE_KEY_SYS_CORP}, vo);
	    return list;
	}
    
	/**
	 * 删除一个组织机构，逻辑删除
	 * @param organId
	 * @param user
	 * @author:lan
	 * @email:763836737@qq.com
	 */
    @CacheEvict(value=GlobalConst.CACHE_KEY_BASE_ORGAN, key="#user.getCorpId()")
    @Transactional
    public void delBaseOrgan(String organId, SysUserEntity user) {
	 	BaseOrganEntity entity = new BaseOrganEntity();
	 	entity.setOrganId(organId);
    	// 后台校验
        // 1:如果存在下级机构，不能删除
	 	this.check("baseOrgan.getChildOrganCount", entity, "该机构存在下级机构，不能删除！");
        // 2:如果该机构下已存在用户，不能删除
	 	this.check("baseOrgan.getOrganUserCount", entity, "该机构已分配用户，不能删除！");
        entity = commonEntityDao.find(organId, BaseOrganEntity.class);
        entity.setEnabledSt(EnabledSt.DISABLE.getFlag());  // 停用状态
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        commonEntityDao.update(entity);
        
        // 删除数据权限 upt by jeffxu 150326
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("resDataId", organId);
        commonEntityDao.deleteByParamsIgnoreNullValue(SysAuthorityResourceEntity.class, map);
    }
    
    /**
     * 已知父节点，求父节点下的子节点数
     * @param parentOrganId
     * @param user
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public Integer getChildNodeCnt(String parentOrganId, SysUserEntity user) {
        String corpId = user.getCorpId();
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("corpId", corpId);
        map.put("parentOrganId", parentOrganId);
        
        Integer count = (Integer) sqlMapDao.selectOne("baseOrgan.getChildNodeCnt", map);
        return count;
    }
    
    /**
     * 获取左侧机构-线路-车 树
     * @param roleIdList
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("unchecked")
    public List<LeftOrgVo> getLeftOrg4Car(List<SysRoleEntity> roleIdList){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("roleIdList", roleIdList);
        List<LeftOrgVo> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseOrgan.getLeftOrg4Car",map), LeftOrgVo.class);
        return list;
    }
    
    /**
     * 获取左侧机构、线、车、驾驶员
     * @param roleIdList
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("unchecked")
    public List<LeftOrgVo> getLeftOrg4Driver(List<SysRoleEntity> roleIdList){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("roleIdList", roleIdList);
        List<LeftOrgVo> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseOrgan.getLeftOrg4Driver",map), LeftOrgVo.class);
        return list;
    }
    
    /**
     * 获取左侧机构、线
     * @param roleIdList
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
     
    @SuppressWarnings("unchecked")
    public List<LeftOrgVo> getLeftOrg4Line(List<SysRoleEntity> roleIdList){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("roleIdList", roleIdList);
        List<LeftOrgVo> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseOrgan.getLeftOrg4Line",map), LeftOrgVo.class);
        return list;
    }
    

    /**
     * 校验机构资源权限
     * @param organId
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public boolean validateOrganInRes(String organId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("resDataId", organId);
        List<SysAuthorityResourceEntity> list = commonEntityDao.findByParamsIgnoreNullValue(SysAuthorityResourceEntity.class, params);
        if(list.size() > 0){
            return true;
        }
        return false;
    }
    
    /**
     * 取得组织机构树
     * @param userId
     * @param organId
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("unchecked")
    public List<BaseOrganEntity> getOrganTree(String userId, String organId){
    	//modidy by qianjy 
    	//修改父节点为汉纳森的用户,替换为顶级节点,使得可以查看整棵树
    	if("11013b72246043cdb851389e56c4ef30".equals(organId.trim())
    			||"9a0abd85e067484b805ad9d6ffe3c3fe".equals(organId.trim())
    			||"d0139cf209bb4cce847271affa221718".equals(organId.trim())){
    		organId="07c81b83eb5e4786ba524c9c0f09c15f";
    	}
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("organId", organId);
        List<BaseOrganEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseOrgan.getOrganTree", map), BaseOrganEntity.class);
    	return list;
    }
    
    /**
     * 获取左侧机构、线、车、驾驶员
     * @param searchConditionVo
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("unchecked")
    public List<LeftOrgVo> getLeftOrg4Driver(SearchConditionVo searchConditionVo){
        List<LeftOrgVo> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseOrgan.getLeftOrg4DriverVo",searchConditionVo), LeftOrgVo.class);
        return list;
    }
    
    /**
     * 获取左侧机构、线
     * @param searchConditionVo
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("unchecked")
    public List<LeftOrgVo> getLeftOrg4Line(SearchConditionVo searchConditionVo){
        List<LeftOrgVo> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseOrgan.getLeftOrg4LineVo",searchConditionVo), LeftOrgVo.class);
        return list;
    }
     
    /**
     * 获取左侧机构-线路-车 树
     * @param searchConditionVo
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("unchecked")
    public List<LeftOrgVo> getLeftOrg4Car(SearchConditionVo searchConditionVo){
        List<LeftOrgVo> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseOrgan.getLeftOrg4CarVo",searchConditionVo), LeftOrgVo.class);
        return list;
    }

    /**
     * 根据省id获取对应市信息
     * @param ProvinceId 省id
     * @return 市信息
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @SuppressWarnings("unchecked")
    @Transactional
    public   List<SysCodeDscEntity> getCityByProvinceId(String ProvinceId){
        List<SysCodeDscEntity> list = PubUtil.convertListMapToObject(sqlMapDao.selectList("baseOrgan.getCityByProvinceId", ProvinceId), SysCodeDscEntity.class);
        return list;
    }

    /**
     * @param roleIdList
     * @return
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     * @创建日期:2014-7-17
     * @功能说明：获取数据权限
     */
    @SuppressWarnings("unchecked")
    public List<String> getAuthorityResource(List<SysRoleEntity> roleIdList){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("roleIdList", roleIdList);
        List<SysAuthorityResourceEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseOrgan.getAuthorityResource",map), SysAuthorityResourceEntity.class);
        List<String> organIdlist = new ArrayList<String>();
        if(PubUtil.isNotEmpty(list)){
            for(SysAuthorityResourceEntity entity : list){
                organIdlist.add(entity.getResDataId());
            }
        }
        return organIdlist;
    }
}
